(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.dataPatch.createRejectController', createRejectController);
	createRejectController.$inject = [ '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'dataPatchService' ];
	function createRejectController($scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, dataPatchService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.dataPatch = {};
		ctrl.dataPatch.dPatchParms = ctrl.dataPatch.dPatchParms || [];
		ctrl.dataPatch.patchTemplate = ctrl.dataPatch.patchTemplate || {};
		ctrl.parms = [];

		ctrl.init = function() {
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.dPatchParms.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.dataPatch.dPatchParms';
			
			authService.createReject(params).then(function(response) {
				dataPatchService.initOptions(ctrl).then(function(result){
					if (response.data && response.data.model && response.data.task) {
						ctrl.dataPatch = response.data.model;
						ctrl.dataPatch.taskId = response.data.task.taskId;
					}
				});
			});
		};

		ctrl.isShow = function (){
			return false;
		};
		
		// return ${},${}
		ctrl.filter = function (string) {
			var subParm;
			if (string != null){
				var m = string.indexOf('$');
				var n = string.indexOf('}');
				if ( m != -1){
					subParm = string.substring(m, n+1);
					ctrl.parms.push(subParm);
					if (string.length >= n){						
						string = string.substring(n +1, string.length);
						ctrl.filter(string);
					}
				}
			}
			return ctrl.parms;
		};
		
		ctrl.checkParmVaule = function (){
			var m = 0;
			var values = [];
			ctrl.dataPatch = ctrl.dataPatch ||[];
			ctrl.dataPatch.patchTemplate = ctrl.dataPatch.patchTemplate ||{};
			ctrl.dataPatch.dPatchParms = ctrl.dataPatch.dPatchParms || [];
			if (ctrl.dataPatch.dPatchParms){				
				angular.forEach(ctrl.dataPatch.dPatchParms, function (value, key){
					if (!value.paramValue ) {
						return ;
					} else {					
						this.push(value.paramValue);
						m++;
					}
				},values); 
				return values;
			}
		};
		
		ctrl.doRefresh = function (){
			ctrl.dataPatch = ctrl.dataPatch ||[];
			ctrl.dataPatch.patchTemplate = ctrl.dataPatch.patchTemplate ||{};
			ctrl.dataPatch.dPatchParms = ctrl.dataPatch.dPatchParms || [];
			if (ctrl.dataPatch.dPatchParms){				
				var values = ctrl.checkParmVaule();
				if ( ctrl.dataPatch.dPatchParms.length === values.length){				
					ctrl.dataPatch.patchTemplate.sqlScript = ctrl.dataPatch.patchTemplate.sqlScript;
					if (ctrl.dataPatch.patchTemplate.sqlScript){						
						var parm = ctrl.dataPatch.patchTemplate.sqlScript.toString();
						var parms = ctrl.filter(parm);
						for ( var i=0; i<parms.length; i++){
							var fullParm = "\\" + parms[i];
							var fullValue;
							var parmName = parms[i].substring(2,parms[i].length-1);
							angular.forEach(ctrl.dataPatch.dPatchParms, function (parmWithValue, key){
								if(parmName == parmWithValue.parmName){
									fullValue = parmWithValue.paramValue;
								}
							});
							var reg = new RegExp(fullParm, "g");
							parm = parm.replace(reg, "\'" + fullValue + "\'");
						}
						ctrl.dataPatch.finalSqlScript = parm;
					}
				} else {
					modalService.openErrorDialogs({
						'messages' : [ 'dataPatch.sqlScript.required']
					});
				}
			}
		};
			
		ctrl.doPreview = function (){
			var values = ctrl.checkParmVaule();
			if ( ctrl.dataPatch.dPatchParms.length === values.length){
				//DML cooperation in database
				ctrl.dataPatch.finalSqlScript = ctrl.dataPatch.finalSqlScript;
				if (ctrl.dataPatch.finalSqlScript != null){
					ctrl.dataPatch.previewTime = ctrl.dataPatch.previewTime;
					return authService.makerPreview(ctrl.dataPatch).then(checkSuccessful, checkFailed);
				} else {
					modalService.openInfoDialogs({
						'messages' : [ "js.info.common.refresh-button-first"]
					});
				}
			} else {
				modalService.openErrorDialogs({
					'messages' : [ 'dataPatch.sqlScript.required']
				});
			}
		};
		
		ctrl.createRejectSave = function() {
			var values = ctrl.checkParmVaule();
			if ( ctrl.dataPatch.dPatchParms.length === values.length){
				return authService.createRejectSave(ctrl.dataPatch).then(saveSuccessful, saveFailed);
			} else {
				modalService.openErrorDialogs({
					'messages' : [ 'dataPatch.sqlScript.required']
				});
			}
			
		};

		ctrl.createRejectSubmit = function() {
			var values = ctrl.checkParmVaule();
			if (ctrl.dataPatch.previewResult != null){				
				if ( ctrl.dataPatch.dPatchParms.length === values.length){
					return authService.createRejectSubmit(ctrl.dataPatch).then(submitSuccessful, submitFailed);
				} else {
					modalService.openErrorDialogs({
						'messages' : [ ' dataPatch.sqlScript.required']
					});
				}
			} else {
				modalService.openErrorDialogs({
					'messages' : [ "js.info.common.preview-button-first"]
				});
			}
			
		};
		
		ctrl.createRejectCancel = function() {
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.cancel', args : [ctrl.dataPatch.primaryKey]} ],
				'btnCallback' : {
					'ok' : function() {
						authService.createRejectCancel(ctrl.dataPatch).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};
		
		$scope.$on("PATCHTEMPLATE.DPATCHNAME_OK", function(event, param) {
			var returnEntities = param.returnEntities;
			if(angular.isArray(returnEntities) && returnEntities[0] && returnEntities[0].dpatchTplId != ctrl.dataPatch.oldDpatchTplId) {
				ctrl.dataPatch.oldDpatchTplId = returnEntities[0].dpatchTplId;
				ctrl.dataPatch.dPatchParms = returnEntities[0].dPatchTplParms || [];
				ctrl.dataPatch.patchTemplate = angular.copy(returnEntities[0]);
				ctrl.dataPatch.finalSqlScript = null;
				ctrl.dataPatch.previewResult = null; 
			}
			event.preventDefault();
			event.stopPropagation();
		});
		
		ctrl.addDPTplParm = function() {
			ctrl.dataPatch.dPatchParms.push({
			});
		};

		ctrl.removeDPTplParm = function() {
			angular.forEach(ctrl.selectedDPParmList, function(selectedDPParm, key) {
				angular.forEach(ctrl.dataPatch.dPatchParms, function(DPParm, index) {
					if (DPTplParm._index == selectedDPParm._index) {
						ctrl.dataPatch.dPatchParms.splice(index, 1);
					}
				});
			});
		};
		
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedDPParmList = selectedRows;
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.datapatch.list',
					'state' : 'cda.dataPatch.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				ctrl.dataPatch = response.data.model;
			}
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function checkSuccessful(response) {
			if (response.data.message) {
				if ( "invalid SQL statement" == response.data.message){
					modalService.openErrorDialogs({
						'messages' : [response.data.message]
					});
				} else {
					ctrl.dataPatch.previewResult = response.data.message;
					ctrl.dataPatch.previewTime = response.data.previewTime;
				}
			}
		}

		function checkFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.cancel' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.datapatch.list',
					'state' : 'cda.dataPatch.list',
					'params' : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);
